import { getCategories, getServiceCategory } from '@/api/home'
import { View, Image, Text } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useEffect, useState } from 'react'
import { AtTabs, AtTabsPane } from 'taro-ui'

const ServiceCard: React.FC<{ product: ProductCard }> = ({ product }) => {

  const handleToService = (serviceId: number, serviceName: string) => {
    Taro.navigateTo({
      url: `/pages/service-list/index?serviceId=${serviceId}&serviceName=${serviceName}`
    })
  }

  return (
    <View className='flex gap-x-3 flex-wrap bg-white shadow mt-2 rounded-md p-2' onTap={() => handleToService(product.serviceId, product.title)} >
      <Image src={product.pic} className='w-16 h-16' />
      <View>
        <Text className='text-2xl'>{product.title}</Text>
        <View className='text-red-500 flex gap-x-1 items-center'>
          <Text className='text-xs'>价格低至</Text>
          <Text className='text-xl'>{product.price}</Text>
          <Text className='text-xs'>元起</Text>
        </View>
      </View>
    </View>
  )
}

export default function Service() {

  const [state, setState] = useState<number | undefined>(undefined);

  const handleClick = (value: number) => setState(value);

  const [categoryList, setCategoryList] = useState<CategoryList[]>([]);
  const [serviceCategoryList, setServiceCategoryList] = useState<ServiceCategoryList[]>([]);

  useEffect(() => {
    const fetchCategories = async () => {
      const { data } = await getCategories()
      setCategoryList(data);
    }

    const fetchServiceCategory = async () => {
      const { data } = await getServiceCategory();
      setServiceCategoryList(data);
    }

    fetchCategories();
    fetchServiceCategory();
  }, [])

  const tabList = categoryList.map(category => ({
    id: category.id,
    title: category.category,
  }));

  const propsArr: HomeCardProps[] = serviceCategoryList.map(serviceCategory => ({
    categoryId: serviceCategory.categoryId,
    title: serviceCategory.categoryName,
    product: serviceCategory.serviceList.map(service => ({
      serviceId: service.serviceId,
      pic: service.pic,
      price: service.lowestPrice,
      title: service.serviceName
    }))
  }))

  return (
    <View className='service'>
      <AtTabs
        current={state!}
        scroll
        height='100vh'
        tabDirection='vertical'
        tabList={tabList}
        onClick={handleClick}
      >

        {propsArr.map((props, index) => (
          <AtTabsPane tabDirection='vertical' current={state!} index={index} key={index} className='p-2 bg-gray-100'>
            {props.product.map((product, idx) => (
              <ServiceCard key={idx} product={product} />
            ))}
          </AtTabsPane>
        ))}

      </AtTabs>
    </View>
  )
}
